import {View, Text} from '@tarojs/components'
import Taro, {useLoad, useRouter} from '@tarojs/taro'
import {ChatEmulator, ChatKnowledge, ChatVoice} from "@/components";
import { useConservationSelector, useDispatchConservation } from "@/hooks/conservation"
import {ChatMessage} from "@/types/conservationType";
import {Tabs, Navbar, Flex, Loading, Cell} from "@taroify/core";
import {ArrowLeft} from "@taroify/icons";
import { useState} from "react";
import './index.css'


export default function AgentConservation() {
  const router = useRouter();
  const conservation_uuid = router.params.uuid;
  const dispatchConservation = useDispatchConservation();
  const conservationDetail = useConservationSelector(state => state.conservation.conservationDetail);
  const generatingTask = useConservationSelector(state => state.conservation.generatingTask);

  const returnDialoguePage = async () => {
    await Taro.navigateBack({
      delta: 1
    })
  };

  // 加载数据
  useLoad(() => {
    Taro.hideShareMenu().then(() => console.log("hide shareMenu"));
    if (conservation_uuid) {
      dispatchConservation.getConservationDetail(conservation_uuid);
    }
  });

  // 发送消息
  const handleSendMessage = (message: ChatMessage) => {
    if(conservationDetail){
      dispatchConservation.setConservationPartialInfo(
        {chat_history: [...conservationDetail.chat_history, message, {role: 'system', contents: [{type: 'progress', content: '25'}]}]})
      dispatchConservation.generateAgentAnswer(conservationDetail.uuid, {message: message.contents})
    }
  };

  const handleGenerateStop = () => {
    if (generatingTask && generatingTask.readyState === generatingTask.OPEN) {
      generatingTask.close({ reason: 'User interrupted' });
      console.log('WebSocket connection closed by user');
    }
  };

  const windowInfo = Taro.getWindowInfo();
  const statusBarHeight = windowInfo.statusBarHeight;
  const [value, setValue] = useState(1);

  return (
    <View style={{height: '100vh', width: '100vw'}}>
      <Navbar
        style={{
          paddingTop: `${(statusBarHeight || 0) + 50}rpx`,
          background: 'linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%)',
          boxShadow: '0 2rpx 10rpx rgba(0, 0, 0, 0.1)',
        }}
      >
        <Navbar.NavLeft icon={<ArrowLeft onClick={returnDialoguePage} size={25} color='black' />} />
        <Navbar.Title style={{ fontSize: '35rpx', color: 'black', fontWeight: 'bold' }}>
          {conservationDetail ? conservationDetail.agent.name : "加载中..."}
        </Navbar.Title>
      </Navbar>

      <View style={{ width: '100%', height: `calc(100% - ${(statusBarHeight || 0) + 150}rpx)`}}>
        <Tabs value={value} onChange={setValue}>
          <Tabs.TabPane title='来源'>
            <View style={{height: `calc(100vh - ${(statusBarHeight || 0) + 230}rpx)`, width: '100%'}}>
              {conservationDetail ? <ChatKnowledge knowledge_base_uuid={conservationDetail.knowledge_base_uuid} note_collection_uuid={conservationDetail.collection_uuid} /> :
                <Flex justify='center'> <Loading size='24px' direction='vertical'>加载中...</Loading></Flex>
              }
            </View>
          </Tabs.TabPane>
          <Tabs.TabPane title='聊天'>
            <View style={{height: `calc(100vh - ${(statusBarHeight || 0) + 230}rpx)`, width: '100%'}}>
              {conservationDetail ? <ChatEmulator conservation={conservationDetail} onSend={handleSendMessage} onStop={handleGenerateStop} /> :
                <Flex justify='center'> <Loading size='24px' direction='vertical'>加载中...</Loading></Flex>
              }
            </View>
          </Tabs.TabPane>
          <Tabs.TabPane title='语音' style={{height: '100%'}}>
            <Cell style={{height: `calc(100vh - ${(statusBarHeight || 0) + 230}rpx)`}}>
              {conservationDetail ? <ChatVoice conservation={conservationDetail} onSend={handleSendMessage} /> : <Text>加载中</Text>}
            </Cell>
          </Tabs.TabPane>
        </Tabs>
      </View>
    </View>
  );
}
